package com.miao.util.regex;

import java.util.StringTokenizer;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Created by miao on 2015/4/10.
 */
public class RegexUtils {
    public static final String REGX_MOBILE = "^[1][3,5,8]+\\d{9}";
    public static final String REGX_NUM = "^[0-9]*[1-9][0-9]*$";
    public static final String REGX_PASS = "\\d{6,16}";
    public static final String REGX_EMAIL = "^[a-zA-Z0-9_]+([-+.][a-zA-Z0-9_]+)*@[a-zA-Z0-9_]+([-.][a-zA-Z0-9_]+)*\\.[a-zA-Z0-9_]+([-.][a-zA-Z0-9_]+)*$";
    public static final String REGX_IP = "^(1\\d{2}|2[0-4]\\d|25[0-5]|[1-9]\\d|[1-9])\\.(1\\d{2}|2[0-4]\\d|25[0-5]|[1-9]\\d|\\d)\\.(1\\d{2}|2[0-4]\\d|25[0-5]|[1-9]\\d|\\d)\\.(1\\d{2}|2[0-4]\\d|25[0-5]|[1-9]\\d|\\d)$";
    public static final String REGX_FILE = "(?!^\\s+|.*\\s$)(^[^/////////://*//?///\"//<//>//|\\\\]{1,255}$)";
    public static final String REGX_CHINESE = "^[\\u4e00-\\u9fa5]+$";
    public static final String REGX_ADDRESS = "((http|ftp|https)://)(([a-zA-Z0-9\\._-]+\\.[a-zA-Z]{2,6})|([0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}))(:[0-9]{1,4})*(/[a-zA-Z0-9\\&%_\\./-~-]*)?";
    private String modale = "";

    public RegexUtils(String modale) {
        if (modale != null)
            this.modale = modale;
    }

    public static boolean verify(String modle, String cxt) {
        boolean flag = false;
        Pattern p = Pattern.compile(modle);
        Matcher m = p.matcher(cxt);
        flag = m.matches();
        return flag;
    }

    public static void main(String[] args) {
//        System.out.println(RegexUtils.verify(RegexUtils.REGX_MOBILE, "18817389905"));
//        System.out.println(RegexUtils.verify(RegexUtils.REGX_CHINESE, "问"));
        System.out.println(RegexUtils.verify(RegexUtils.REGX_ADDRESS,"http://www.baidu.com"));
    }

    public static String[] split(String source, String delim) {
        String[] arr = new String[0];
        if (source == null) {
            return arr;
        }
        if (delim == null) {
            delim = ",";
        }
        StringTokenizer st = new StringTokenizer(source, delim);
        int total = st.countTokens();
        arr = new String[total];
        for (int i = 0; i < total; i++) {
            arr[i] = st.nextToken();
        }
        return arr;
    }

    public RegexUtils replace(String key, String value) {
        String keyModle = "\\$\\{" + key + "\\}";
        this.modale = this.modale.replaceAll(keyModle, value);
        return this;
    }

    public String toString() {
        return this.modale;
    }
}
